package com.jic.point.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jic.common.base.vo.PageResult;
import com.jic.point.constant.consist.ResponseCode;
import com.jic.point.exception.AppRuntimeException;
import com.jic.point.mapper.*;
import com.jic.point.model.entity.ConfBd;
import com.jic.point.model.entity.ConfBdApply;
import com.jic.point.model.entity.ConfPlatform;
import com.jic.point.model.vo.response.ConfBdResponse;
import com.jic.point.model.vo.response.ConfPlatformResponse;
import com.jic.point.rest.request.SignData;
import com.jic.point.service.ConfBdService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 接口实现类
 *
 * @author : tzc
 * @version : v1.0.0
 * @email :
 * @since : 2020-03-09 10:12:20
 */
@Service
@Slf4j
public class ConfBdServiceImpl implements ConfBdService {

	@Resource
	private ConfBdMapper mapper;
	@Resource
    ConfBdApplyMapper confBdApplyMapper;

	@Resource
	private ConfBdPointLogMapper confBdPointLogMapper;

	@Resource
	private ConfBdMoneyLogMapper confBdMoneyLog;

	@Resource
	private ConfBdReconciliationMapper confBdReconciliationMapper;

	@Resource
	private ConfPlatformMapper confPlatformMapper;


    @Override
    public int insertSelective(ConfBd confBd) {
        int flag = mapper.insertSelective(confBd);
        if (flag == 1) {
            return 1;
        }else {
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "新增失败");
        }
    }

    /**
	 * 新增记录
	 *
	 * @param request 需要保存的入参实体类
	 * @return int 是否保存成功
	 */
	@Override
	public int save(ConfBd request) {
	 int flag = mapper.insert(request);
	 if (flag == 1) {
	   return 1;
	 }else {
	   throw new AppRuntimeException(ResponseCode.EXCEPTION, "新增失败");
	 }
	}


	/**
	 * 保存或修改记录信息
	 * @param request 需要保存的入参实体类
	 * @return int 是否保存或修改成功
	 * author tzc
	 * @date 2020-3-11 20:54:09
	 */
	@Override
	public int saveOrUpdate(ConfBd request){
		log.info("保存或修改记录信息，入参 = {}", JSONObject.toJSONString(request));
		try {
			if (request == null) {
				throw new AppRuntimeException(ResponseCode.EXCEPTION,"入参为空");
			}

			if (request.getId() != null) {
				log.info("保存或修改记录信息，修改，入参 = {}", JSONObject.toJSONString(request));
				//编辑=操作-------主表逻辑删除---------插入到申请表中
                //申请表信息
                ConfBdApply confBdApply = new ConfBdApply();
                BeanUtils.copyProperties(request, confBdApply);
                confBdApply.setApplierId(request.getAdminOperate().getOperator());
                deleteByPrimaryKeyLogically(request);
                //设置相对应的字段属性
                confBdApply.setCurrentAction(1);
                confBdApply.setDeleteFlag(0);
                confBdApply.setAuditSts(0);
				int flag = confBdApplyMapper.insertSelective(confBdApply);
				if(flag == 1){
				  return 1;
				}
			}else{
				log.info("保存或修改记录信息，保存，入参 = {}", JSONObject.toJSONString(request));
                //申请表信息
                ConfBdApply confBdApply = new ConfBdApply();
                BeanUtils.copyProperties(request, confBdApply);
//                List<ConfBdApply> list = confBdApplyMapper.selectBySelective(confBdApply);
//                for (ConfBdApply cba:list
//                     ) {
//                    if(cba.getCode() == request.getCode()){
//                        throw new AppRuntimeException(ResponseCode.EXCEPTION, "已存在相同的BD编码关系，请重新选择！");
//                    }
//                }
                //查询主表审核通过的信息 and 申请表添加的信息 --------存在，增加不成功

                confBdApply.setApplierId(request.getAdminOperate().getOperator());
                confBdApply.setDeleteFlag(0);
                confBdApply.setCurrentAction(0);
                confBdApply.setAuditSts(0);
                int flag = confBdApplyMapper.insertSelective(confBdApply);
				if(flag == 1){
				  return 1;
				}else{
				  throw new AppRuntimeException(ResponseCode.EXCEPTION,"修改失败");
				}
			}
		} catch (Exception e) {
			log.error("用户保存或修改失败", e);
			throw new AppRuntimeException(ResponseCode.EXCEPTION,"用户保存或修改失败");
		}
	     return -1;
	}

    @Override
    public int saveOrUpdateApply(ConfBd request) {
        log.info("保存或修改记录信息，入参 = {}", JSONObject.toJSONString(request));
        try {
            if (request == null) {
                throw new AppRuntimeException(ResponseCode.EXCEPTION,"入参为空");
            }
            if (request.getId() != null) {
                log.info("保存或修改记录信息，修改，入参 = {}", JSONObject.toJSONString(request));
                int flag = mapper.updateByPrimaryKeyApply(request);
                if(flag == 1){
                    return 1;
                }
            }
        } catch (Exception e) {
            log.error("用户保存或修改失败", e);
            throw new AppRuntimeException(ResponseCode.EXCEPTION,"用户保存或修改失败");
        }
        return -1;
    }

    /**
	 * 删除记录
	 *
	 * @param request 需要删除,含有主键的入参实体类
	 * @return int 是否删除成功
	 */
	@Override
	public int deleteByPrimaryKey(ConfBd request) {
		int flag = mapper.deleteByPrimaryKey(request);
	    if (flag == 1) {
	      return 1;
	    }else {
	      throw new AppRuntimeException(ResponseCode.EXCEPTION, "删除失败");
	    }
	}


	/**
	 * 逻辑删除记录
	 *
	 * @param request 含有主键的逻辑删除实体类
	 * @return int 是否逻辑删除成功
	 */
	@Override
	public int deleteByPrimaryKeyLogically(ConfBd request) {
		request.setDeleteFlag(1);
		int flag = mapper.updateByPrimaryKey(request);
	    if (flag == 1) {
	      return 1;
	    }else {
	      throw new AppRuntimeException(ResponseCode.EXCEPTION, "逻辑删除记录失败");
	    }
	}


	/**
	 * 修改
	 *
	 * @param request
	 * @return
	 */
	@Override
	public int updateByPrimaryKeySelective(ConfBd request){
		try {
			log.info("修改记录");
			ConfBd param = new ConfBd();
			BeanUtils.copyProperties(request, param);
			int flag = mapper.updateByPrimaryKeySelective(param);
	        if (flag == 1) {
	         return 1;
	        }else {
	          throw new AppRuntimeException(ResponseCode.EXCEPTION, "修改记录失败");
	        }
		} catch (Exception e) {
			log.error("修改记录失败", e);
			throw new AppRuntimeException(ResponseCode.EXCEPTION,"修改记录失败");
		}

	}

	/**
	 * 记录详情
	 *
	 * @param request 查询的入参实体类
	 * @return 数据库查询到的实体类
	 */
	@Override
	public ConfBd getByPrimaryKey(ConfBd request) {
		return mapper.selectByPrimaryKey(request);
	}

	@Override
	public ConfBd getByode(ConfBd confBd) {
		return mapper.selectByode(confBd);
	}


	/**
	 * 分页查询
	 *
	 * @param request 分页查询入参实体类
	 * @return 含有分页信息的实体类列表
	 */
	@Override
	public PageInfo<ConfBd> listPageBySelective(ConfBd request, int pageNum, int pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		PageHelper.orderBy(" update_time desc");
		List<ConfBd> list = mapper.listPageBySelective(request);
		List<ConfBd> collect = list.stream().map(item -> {
			item.setDistribution(item.getAvailable().subtract(item.getFrozen()));
			item.setAvailable(item.getTotal().subtract(item.getFrozen()));
			return item;
		}).collect(Collectors.toList());
		PageInfo pageInfo = new PageInfo(collect);
		PageResult<ConfBd> result = new PageResult<>();
		result.setTotal(pageInfo.getTotal());
		result.setRows(collect);
		return new PageInfo(collect);
	}

	/**
	 * 不分页查询
	 *
	 * @param request 不分页查询入参实体类
	 * @return 数据库查到的实体类列表
	 */
	@Override
	public List<ConfBd> listAllRecord(ConfBd request) {
		//分页处理
		request.setDeleteFlag(0);
		return mapper.selectBySelective(request);
	}

	@Override
	public List<ConfBdResponse> query() {
		return mapper.query();
	}

	@Override
	public int updateByCode(ConfBd confBd) {
		return mapper.updateByCode(confBd);
	}

	@Override
	public List<ConfBd> selConfBdByCode(SignData signData) {
		return mapper.selConfBdByCode(signData);
	}

	@Override
	public BigDecimal queryAvailablePoint(String busiCode) {
		return mapper.queryAvailablePoint(busiCode);
	}

	@Override
	public List<ConfBdResponse> getTree() {
		ConfBd bd = new ConfBd();
		bd.setDeleteFlag(0);
		List<ConfBd> confBds = mapper.selectBySelective(bd);
		List<ConfBdResponse> collect1 = confBds.stream().map(item -> {
			ConfBdResponse confBdResponse = new ConfBdResponse();
			BeanUtils.copyProperties(item, confBdResponse);
			return confBdResponse;
		}).collect(Collectors.toList());
		for (int i=0;i<collect1.size();i++) {
			List<ConfPlatform> platformList = confPlatformMapper.selectByPrimaryBdCode(confBds.get(i).getCode());
			List<ConfPlatformResponse> collect = platformList.stream().map(item -> {
				ConfPlatformResponse response = new ConfPlatformResponse();
				BeanUtils.copyProperties(item, response);
				return response;
			}).collect(Collectors.toList());
			collect1.get(i).setList(collect);
		}
		return collect1;
	}

	@Override
	public Boolean virtual(ConfBd confBd) {
		return null;
	}

	@Override
	public int dbPointDeduction(ConfBd confbd) {
		return mapper.dbPointDeduction(confbd);
	}


//	public List<Date> date(){
//List<Date>list = new ArrayList<>();
//		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
//		Calendar firstDay= Calendar.getInstance();//获取当前时间
//		firstDay.add(Calendar.MONTH, -1);
//		firstDay.set(Calendar.DAY_OF_MONTH, 1);//日期设置为一号，就是第一天了
//		String format = simpleDateFormat.format(firstDay.getTime());
//		//计算本月最后一天
//		Calendar lastDay= Calendar.getInstance();//获取当前时间
//		lastDay.set(Calendar.DAY_OF_MONTH, 1);//日期设置为一号，就是第一天了
//		String format1 = simpleDateFormat.format(lastDay.getTime());
//
//		try {
//			list.add(simpleDateFormat.parse(format));
//			list.add(simpleDateFormat.parse(format1));
//		} catch (ParseException e) {
//			e.printStackTrace();
//		}
//		return list;
//	}


}
